package cn.uil.demo2;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

@Component
public class AsyncBeanScanner implements BeanDefinitionRegistryPostProcessor {

    private final Set<String> asyncBeanNames = new HashSet<>();

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        // 扫描所有带@AsyncInit注解的类
        ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
        scanner.addIncludeFilter(new AnnotationTypeFilter(AsyncInit.class));

        scanner.findCandidateComponents("com.your.package").forEach(beanDefinition -> {
            String beanName = beanDefinition.getBeanClassName();
            asyncBeanNames.add(beanName);
        });
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        // 将收集的Bean名称注册为单例Bean，供后续使用
        beanFactory.registerSingleton("asyncBeanNames", asyncBeanNames);
    }
}
